/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */


#include "addressbar.h"

#include <QApplication>
#include <QPainter>

AddressBar::AddressBar(QWidget* parent) : QWidget(parent)
{
	m_font = qApp->font();
}

AddressBar::~AddressBar()
{
}

void AddressBar::addElement(const AddressBarElementPtr& element)
{
	m_elements.append(element);
	regenerateSubwidgets();
	update();
}

void AddressBar::clear()
{
	m_elements.clear();
	regenerateSubwidgets();
}

QSize AddressBar::minimumSizeHint() const
{
	if(m_elements.isEmpty())
		return QSize(100, 0);
	return QSize(100, QFontMetrics(m_font).lineSpacing() * 2);
}

QSize AddressBar::sizeHint() const
{
	if(m_elements.isEmpty())
			return QSize(16000000, 0);
	return QSize(16000000, QFontMetrics(m_font).lineSpacing() * 2);
}

void AddressBar::paintEvent(QPaintEvent* event)
{
	QPainter p(this);

	foreach(const Subwidget& w, m_subwidgets)
	{
		if(w.element)
		{
			p.drawText(w.rect, Qt::AlignCenter | Qt::AlignVCenter, w.element->text());
		}
		else
		{
			p.drawText(w.rect, Qt::AlignCenter | Qt::AlignVCenter, w.text);
		}
	}
}

void AddressBar::regenerateSubwidgets()
{
	m_subwidgets.clear();
	QList<AddressBarElementPtr>::iterator it = m_elements.begin();
	if(it == m_elements.end())
		return;

	QFontMetrics metrics(m_font);

	int x = LeftMargin;
	do
	{
		int textwidth = metrics.width((*it)->text());
		Subwidget element;
		element.element = (*it);
		element.rect = metrics.boundingRect(x, 0, textwidth, height(), Qt::AlignCenter | Qt::AlignVCenter, (*it)->text());
		m_subwidgets.append(element);

		++it;

		if(it == m_elements.end())
			break;

		x += (textwidth + ElementSpacing);
		textwidth = metrics.width(">");

		Subwidget arrow;
		element.text = ">";
		element.rect = metrics.boundingRect(x, 0, textwidth, height(), Qt::AlignCenter | Qt::AlignVCenter, ">");
		m_subwidgets.append(arrow);

		x += (textwidth + ElementSpacing);
	} while(it != m_elements.end());
}
